package com.liu.android.gitee.net;

import com.google.gson.Gson;
import com.liu.android.gitee.app.Constant;
import com.liu.android.gitee.bean.TokenEntity;
import com.liu.android.gitee.utils.SPUtil;

import java.io.IOException;

import androidx.annotation.NonNull;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 在请求头里添加token的拦截器处理
 * 刷新过期token
 */
public class TokenHeaderInterceptor implements Interceptor {

    @NonNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        String json_token = SPUtil.getInstance().getString(Constant.TOKEN);
        String token = new Gson().fromJson(json_token, TokenEntity.class).getAccess_token();
        Request originalRequest = chain.request();
        if (token.isEmpty()) {
            return chain.proceed(originalRequest);
        }else {
            Request updateRequest = originalRequest.newBuilder().header(Constant.TOKEN, token).build();
            return chain.proceed(updateRequest);
        }

    }
}